package stuff3D.tools
{
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Vector3D;

	public class RotationNavigator
	{
		static public var instance:RotationNavigator;
		static public var container:DisplayObjectContainer;
		static public var start_selection:Function;
		static public var move_selection:Function;
		static public var release_selection:Function;
		static public var shut:Boolean = false;
		static public var pivot:Vector3D;
		private var start_click:Point;
		private var objet:DisplayObject;
		
		static public function setup( doc:DisplayObjectContainer, obj:DisplayObject, start:Function=null, move:Function=null, release:Function=null ):void
		{
			if ( instance == null ) new RotationNavigator( doc, obj );
			start_selection = start;
			move_selection = move;
			release_selection = release;
		}
		public function RotationNavigator( doc:DisplayObjectContainer, obj:DisplayObject )
		{
			container = doc;
			objet = obj;
			container.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
			instance = this;
		}
		public function mouseDown(event:MouseEvent):void
		{
			if ( shut ) return;
			start_click = new Point( container.mouseX, container.mouseY );
			container.addEventListener(MouseEvent.MOUSE_MOVE, bouge);
			container.addEventListener(MouseEvent.MOUSE_UP, mouseReleased);
			if ( start_selection != null ) start_selection();
		}
		public function mouseReleased(event:MouseEvent):void
		{
			if ( shut ) return;
			container.removeEventListener(MouseEvent.MOUSE_MOVE, bouge);
			container.removeEventListener(MouseEvent.MOUSE_UP, mouseReleased);
			if ( release_selection != null ) release_selection();
		}
		public function bouge(event:MouseEvent):void
		{
			if ( shut ) return;
			var mouse:Point = new Point( container.mouseX, container.mouseY );
			
			var speed:Point = new Point();
			speed.x = ( mouse.x - start_click.x ); 
			speed.y = ( mouse.y - start_click.y ); 
			
			objet.transform.matrix3D.appendRotation( speed.x, new Vector3D(  0, 1, 0 ), pivot ) ; //Vector3D.X_AXIS);
			objet.transform.matrix3D.appendRotation( speed.y, new Vector3D( -1, 0, 0 ), pivot ) ; 
			
			start_click = new Point( container.mouseX, container.mouseY );
			
			if ( move_selection != null ) move_selection();
		}	
	}
}